﻿
using AiMoBridge.Interface;
using AiMoRhino.Pipeline;
using Rhino;
using System;
using System.IO;
using System.Reflection;

namespace AiMoRhino.Main
{
    class AimoStartExternal
    {
        public static bool RunCommand()
        {
            return Instance?.Executor?.RunCommand() ?? false;
        }

        PipeServer pipeServer { get; set; }
        RhinoExecutor Executor { get; }
        static AimoStartExternal Instance { get; set; }


        IBridgeInfo BridgeInfo { get; }
        public AimoStartExternal()
        {
            Instance = this;
            RhinoApp.Closing += RhinoApp_Closing;
            BridgeInfo = new RhinoBridgeInfo();
            Executor = new RhinoExecutor();

        }
        public void StartAimoScript()
        {
            if (pipeServer == null || (!pipeServer.Connected))
            {
                pipeServer?.Dispose();
                pipeServer = new PipeServer(Executor, BridgeInfo);
                string rhpFolder = new FileInfo(Assembly.GetAssembly(typeof(PipeServer)).Location).Directory.FullName;
                string aimoAppExe = Path.Combine(rhpFolder, "lib", "AiMoWindows.exe");
                pipeServer.StartServer(aimoAppExe);
            }
            else
            {
                RhinoApp.WriteLine("Already Started Aimo");
            }
        }

        void RhinoApp_Closing(object sender, EventArgs e)
        {
            pipeServer?.Dispose();
        }

    }
}
